<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入角色名称"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium"
          >搜索
          </el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <perButton label="新建" type="primary" icon="el-icon-plus" size="medium" perms="PT_USER_ADD"
                   @click="handlerAccount"></perButton>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
        >刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        row-key="id"
        border
        style="width: 100%;"
        class="elTable"
      >
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <!--        <el-table-column prop="roleCode" label="角色编码" align="center"/>-->
        <el-table-column prop="projectRoleName" label="角色名称" align="center"/>
        <el-table-column prop="projectRoleDesc" label="角色描述" align="center" show-overflow-tooltip/>
        <el-table-column prop="haveControl" label="控制权限" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.haveControl=='N'?'':'success'">
              {{ scope.row.haveControl=='N'?'没有':'有'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="controlLevelName" label="控制等级" align="center"/>
        <el-table-column prop="createByName" label="创建人" align="center"/>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column prop="updateByName" label="更新人" align="center"/>
        <el-table-column label="更新时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="{ row }">
            <perButton label="标签配置" type="primary" size="mini" perms="PT_USER_EDIT"
                       @click="configTagBtn(row)"></perButton>
            <perButton label="编辑" type="warning" size="mini" perms="PT_USER_EDIT"
                       @click="handlerEdit(row)"></perButton>
            <perButton label="删除" type="danger" size="mini" perms="PT_USER_DEL"
                       @click="handlerDelete(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="getAccountData"
      />
    </el-card>

    <!-- 新建 -->
    <yc-dialog ref="ycDialog" :dialogTitle="dialogTitle" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="newAccountFormRef"
            :rules="newAccountModelRules"
            :model="newAccountModel"
            :disabled="detailsDisabled"
            label-width="90px"
          >
            <el-form-item label="角色名称" prop="projectRoleName">
              <el-input v-model="newAccountModel.projectRoleName"/>
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input type="textarea" :rows="2" v-model="newAccountModel.projectRoleDesc"/>
            </el-form-item>
            <el-form-item label="控制权限" prop="haveControl">
              <el-select v-model="newAccountModel.haveControl" class="w-100">
                <el-option label="有" :value="'Y'"/>
                <el-option label="没有" :value="'N'"/>
              </el-select>
            </el-form-item>
            <el-form-item label="控制等级" prop="controlCode" v-if="newAccountModel.haveControl=='Y'">
              <el-select v-model="newAccountModel.controlCode" class="w-100">
                <el-option
                  v-for="item in controlLevelData"
                  :key="item.controlCode"
                  :label="item.controlName"
                  :value="item.controlCode"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>


    <!-- 标签配置 -->
    <yc-dialog ref="configDialog" :dialogTitle="dialogTitle" :show-center="false" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-tree
            v-model="newConfigModel.tagCode"
            :data="tagData"
            :props="tagProps"
            show-checkbox
            default-expand-all
            node-key="tagCode"
            ref="roleTag"
            @node-click="handleNodeClick"
          >
          </el-tree>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="configDialogSave">确定</el-button>
        <el-button @click="$refs.configDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"

  import {
    queryPage,
    insertByModel,
    updateByModel,
    deleteByModel,
    queryRoleToTag,
    saveRoleToTag
  } from "@/api/projectBasicsSetup/roleManage"
  import {
    queryList
  } from "@/api/projectBasicsSetup/level"

  export default {
    components: {
      ycDialog,
      perButton
    },
    data() {
      return {
        isGlobalMessageShow: false,
        message: "",

        tableData: [],
        count: 0,
        pageIndex: 1,
        pageSize: 10,
        loading: false,

        searchModel: {
          userName: "",
          status: null //正常/停用状态（全部）
        },

        newAccountModel: {
          projectRoleName: "",
          projectRoleDesc: "",
          haveControl: "",
          controlCode: "",
          id: 0
        },
        newAccountModelRules: {
          projectRoleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
          haveControl: [{ required: true, message: "请选择是否有控制权限", trigger: "change" }],
          controlCode: [{ required: true, message: "请选择控制等级", trigger: "change" }]
        },
        controlLevelData: [],


        dialogTitle: "",
        centerTitle: "",

        newConfigModel: {
          roleCode: "",
          tagCode: []
        },
        newConfigModelRules: {
          tagCode: [{ required: true, message: "请选择标签", trigger: "change" }]
        },
        tagData: [],
        tagProps: {
          children: "childList",
          value: "tagCode",
          label: "tagName",
          multiple: true,
          checkStrictly: true
        },

        detailsDisabled: false,
        addOrUpdateLoading: false
      }
    },
    created() {
      this.getAccountData()
      this.queryListByLevel()
    },
    methods: {
      /**
       * 获取表格方法
       */
      async getAccountData(tableInfo) {
        this.loading = true
        if (tableInfo) {
          const { userName, status } = tableInfo
          const { object } = await queryPage({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            userName,
            status
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const { object } = await queryPage({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },
      // 搜索按钮
      async searchClick() {
        this.getAccountData(this.searchModel)
      },

      /**
       * 删除按钮
       */
      async handlerDelete({ id }) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const { message, status } = await deleteByModel({ id })
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      /**
       * 新建
       * */
      async handlerAccount() {
        this.dialogTitle = "添加"
        this.centerTitle = "添加"

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true

        Object.keys(this.newAccountModel).forEach((item) => {
          this.newAccountModel[item] = ""
        })
        this.newAccountModel.haveControl = "N"
      },

      /**
       * 修改
       */
      async handlerEdit(row) {
        this.dialogTitle = "编辑"
        this.centerTitle = "编辑"

        this.newAccountModel.id = row.id
        this.newAccountModel.projectRoleName = row.projectRoleName
        this.newAccountModel.projectRoleDesc = row.projectRoleDesc
        this.newAccountModel.haveControl = row.haveControl
        this.newAccountModel.controlCode = row.controlLevelCode

        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
      },

      queryListByLevel() {
        queryList().then(res => {
          this.controlLevelData = res.object
        })
      },

      dialogSave() {
        this.$refs.newAccountFormRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            if (this.detailsDisabled) {
              // 详情的确定
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.newAccountModel.id) {
              const { id, projectRoleName, projectRoleDesc, haveControl, controlCode } = this.newAccountModel
              const { message, status } = await updateByModel({
                id,
                projectRoleName,
                projectRoleDesc,
                haveControl,
                controlLevelCode: controlCode
              })
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            } else {
              const { projectRoleName, projectRoleDesc, haveControl, controlCode } = this.newAccountModel
              const { message, status } = await insertByModel({
                projectRoleName,
                projectRoleDesc,
                haveControl,
                controlLevelCode: controlCode
              })
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      // 标签配置
      async configTagBtn(row) {
        this.dialogTitle = "标签配置"
        this.centerTitle = "标签配置"

        this.newConfigModel.roleCode = row.projectRoleCode
        await this.queryRoleToTag(row.projectRoleCode)

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.configDialog.dialogVisible = true

        this.handleSelectedNodes()
      },

      handleSelectedNodes() {
        const selectedIds = []

        function traverse(data) {
          for (let item of data) {
            if (item.messages == "1") { // 假设有一个属性标识是否要回显
              selectedIds.push(item.tagCode)
            }
            if (item.childList && item.childList.length) {
              traverse(item.childList)
            }
          }
        }

        traverse(this.tagData)

        // 使用 nextTick 确保 DOM 更新完毕后再设置选中状态
        this.$nextTick(() => {
          if (this.$refs.roleTag) {
            this.$refs.roleTag.setCheckedKeys(selectedIds)
          }
        })
      },
      handleNodeClick(data, node, vnode) {
        // this.$refs.roleTag.getCheckedNodes().forEach(item => {
        //   if (item.tagCode === data.tagCode) return;
        //   this.$refs.roleTag.setChecked(item.tagCode, false);
        // });
        // this.$refs.roleTag.setChecked(data.tagCode, !this.$refs.roleTag.getCheckedNodes().includes(data))
      },
      async queryRoleToTag(projectRoleCode) {
        const { object } = await queryRoleToTag({
          projectRoleCode: projectRoleCode
        })
        this.tagData = object
      },


      async configDialogSave() {
        const tagCodeList = this.$refs.roleTag.getCheckedNodes()
        this.newConfigModel.tagCode = tagCodeList.map(item => {
          return {
            tagName: item.tagName,
            tagCode: item.tagCode
          }
        })

        if (this.newConfigModel.tagCode.length == 0) {
          this.$message({
            message: "请选择标签",
            type: "warning"
          })
          return
        }
        this.addOrUpdateLoading = true

        const { message, status } = await saveRoleToTag({
          projectRoleCode: this.newConfigModel.roleCode,
          mapString1: JSON.stringify(this.newConfigModel.tagCode)
        })
        if (status == 200) {
          this.getAccountData()
          this.$refs.configDialog.dialogVisible = false
          this.$message.success(message)
        }
        this.addOrUpdateLoading = false
      },

      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {
          userName: "",
          status: null
        }
        this.getAccountData()
      },

      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      }
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }


  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>
